<script>
import HeaderNav from '@/components/HeaderNav.vue'
import TaskContainer from '@/components/TaskContainer.vue'
import TaskItem from '@/components/TaskItem.vue'
import Condition from '@/components/Condition.vue' 
import TaskCodeView from './task/TaskCodeView.vue'
import TaskPreviewView from './task/TaskPreviewView.vue'
import Footor from '@/components/Footor.vue'
import API from '@/api/index.js'
import token from '@/api/token'

export default {
	components: {
		HeaderNav,
		TaskItem,
		TaskContainer,
		Condition,
		TaskCodeView,
		TaskPreviewView,
		Footor,
	},
	data() {
		return {
			conditionList: [
				{
					name: "编程语言",
					value: 'l_name',  // 查询条件对应的键
					list: [
						// { id: "java", name: "Java" },
						// { id: "python", name: "Python" },
					]
				},
				{
					name: "难易程度",
					value: 't_completed',  // 查询条件对应的键
					list: [
						{ id: "简单题", name: "简单题" },
						{ id: "中等题", name: "中等题" },
						{ id: "难题", name: "难题" },
						{ id: "选做题", name: "选做题" },
					],
					multi: true, // 支持多选
				},
				{
					name: "任务状态",
					value: 't_status',  // 查询条件对应的键
					list: [
						{ id: 0, name: "未开始" },
						{ id: 1, name: "进行中" },
						{ id: 2, name: "需讲解" },
						{ id: 3, name: "已提交" },
						{ id: 4, name: "已检查" },
						{ id: -1, name: "异常题"},
						{ id: 5, name: "已完成" }
					],
					multi: true, // 支持多选
				}
			],
			queryList: [],  // 存储关键字 搜索结果
			showDialog: false,
			showPreviewDialog: false,
			searchResults: [], // 存储搜索结果
			isSearching: false, //是否处于 搜索状态
			pagination: {
				page: 1,
				rows: 6,
			},
			pageTotal : 0,
			currentUser: token.getUser(), //获取用户信息
			condition: {}, // 查询关键字条件
			currentPreviewTask: null, // 存储当前预览的任务数据
			dialogWidth: window.innerWidth <= 600 ? '90%' : '70%',
		}
	},
	created() {
		this.QueryTaskList()
		this.getLanguage()
	},
	mounted() {
		window.addEventListener('resize', this.handleResizeDialogWidth);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.handleResizeDialogWidth);
	},
	computed: {
		dialogWidth() {
			return window.innerWidth <= 600 ? '90%' : '70%';
		}
	},
	methods: {
		QueryTaskList() {
			if(this.isSearching) 
				return;
			const queryParams ={
				...this.condition,
				user_id: this.currentUser.id,
				page: this.pagination.page,
				rows: this.pagination.rows
			}
			// console.log(queryParams)
			API.getTaskList(queryParams).then(ret=>{
				this.queryList = ret.data;
				this.pageTotal = ret.total;
				// console.log(this.queryList);
			})
		},
		getLanguage(){
			API.getLanguage(this.currentUser.id)
			.then(ret=>{
				let res  = ret.data
				// console.log(res)
				const languageList = res.map(lang => {
            		// 将name转换为小写作为id，并保持name不变
					return { 
						id: lang.name.toLowerCase(), 
						name: lang.name 
					};
				});
				this.conditionList = [
					{
						name: "编程语言",
						value: 'l_name',
						list: languageList
					},
					...this.conditionList.slice(1) // 保留其他条件
				];
			})
		},
		handleConditionChange() {
			// 重置页码为第一页
			this.pagination.page = 1;
			// 使用当前条件重新加载数据
			this.QueryTaskList(this.condition);
		},
		// 监听页码改变
		handlePageChange(page){
			this.pagination.page = page;
			this.QueryTaskList(this.condition);
		},
		// 
		handleResults(results) {
			this.searchResults = results;
			this.isSearching = true; //标记 为搜索状态
			this.pagination.page = 1;
			this.pageTotal = results.length;
		},
		clearSearchResults(){
			this.isSearching = false; // 取消搜索状态
    		this.searchResults = [];  // 清空搜索结果
    		this.QueryTaskList();     // 重新加载列表
		},
		getLeaveType(completedText) {
			const mapping = {
				'简单题': 1,
				'中等题': 2,
				'难题': 3,
				'选做题': 4
			};
			return mapping[completedText] || 1;
		},
		handlerCode(task) {
			this.currentPreviewTask = task;
			this.showDialog = true;
		},
		previewTask(task) {
			this.currentPreviewTask = task;
			this.showPreviewDialog = true ;
		},
		saveTask(){
			// 通过 ref 可以 调用 子组件 的 submitTask的方法
			this.$refs.taskCodeView.setCodeChecked();
		},
		handleSaveSuccess() {
			this.showDialog = false;
			this.QueryTaskList();
		},
		updateStatus(payload){
			// 修改开始和结束状态
			let {taskId, status} = payload;
			console.log(taskId, status)
			const params = {
				task_id: taskId,
				status: status,
				user_id: this.currentUser.id
			}
			API.update_state(params)
			.then(ret => {
				this.$message.success(status === 0 ? "开始任务成功" : "完成任务成功");
				this.QueryTaskList();  //更新任务列表
			})
		},
		handleResizeDialogWidth() {
			this.dialogWidth = window.innerWidth <= 600 ? '90%' : '70%';
		},
	},
	watch: {
		'condition.search'(newVal) {
			if (!newVal) {
				this.clearSearchResults(); // 搜索词清空时，恢复原始列表
			}
		}
	}
}
</script>

<template>
	<main class="normal-view">
		<!-- 系统导航 -->
		<HeaderNav active-index="0" class="nav-glass"></HeaderNav>
		<div class="glass-background"></div>

		<div class="content-wrapper">
			<!-- 搜索条件 -->
			<Condition :conditionList="conditionList" 
			v-model="condition" 
			@change="handleConditionChange"
			@update-results = "handleResults"
			@clear-search="clearSearchResults"
			class="condition-glass" 
			/>

			<!-- 任务列表 -->
			<div class="task-container-glass">
				<div class="task-items">
					<TaskItem v-for="(task, n) in isSearching ? searchResults : queryList" 
						:key="n" 
						:id="task.id" 
						:leave="getLeaveType(task.completed)" 
						:lang-name="task.l_name" 
						:title="task.title" 
						:status="task.status"
						:module-name="task.m_name"
						@update:code="handlerCode(task)"
						@preview:task="previewTask(task)"
						@change="handleConditionChange"
						@start-task="updateStatus"
						@over-task="updateStatus"
						/>
				</div>

				<!-- 添加分页插件 -->
				<div class="pagination-wrapper">
					<el-pagination background layout="prev, pager, next" hide-on-single-page
						:page-size="pagination.rows" :pager-count="5" v-model:current-page="pagination.page"
						:total="this.pageTotal"
						@current-change="handlePageChange"
						/>
				</div>
			</div>
		</div>
	</main>

	<Footor></Footor>

	<el-dialog v-model="showDialog" title="任务提交" :width="dialogWidth" top="5vh">
    <!-- 添加ref拿到TaskCodeView页面定义的方法 -->
    <TaskCodeView 
      :task = "currentPreviewTask" 
      ref="taskCodeView"
      @answer-update="handleSaveSuccess"
    /> 
    <template #footer>
      <div class="dialog-footer btn-row">
        <el-button type="primary" @click="saveTask">保存</el-button>
        <el-button @click="showDialog = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

	<el-dialog v-model="showPreviewDialog" title="任务预览" :width="dialogWidth">
		<TaskPreviewView :task= "currentPreviewTask"/>  		<!-- 传递预览任务task -->
	</el-dialog>
</template>

<style scoped>
.normal-view {
	min-height: 100vh;
	position: relative;
	background: linear-gradient(135deg, #151824 0%, #1c1f35 100%);
}

.content-wrapper {
	margin: 0 auto;
	padding: 20px 50px;
	position: relative;
	z-index: 1;
}

.glass-background {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-image:
		radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.03) 0%, transparent 1px),
		radial-gradient(circle at 0% 0%, rgba(255, 255, 255, 0.03) 0%, transparent 1px);
	background-size: 24px 24px;
	background-position: 0 0, 12px 12px;
	opacity: 0.5;
	z-index: 0;
}

.nav-glass,
.condition-glass,
.task-container-glass {
	backdrop-filter: blur(12px);
	background: rgba(21, 24, 42, 0.4);
	border: 1px solid rgba(255, 255, 255, 0.05);
	border-radius: 16px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
	margin-bottom: 20px;
	position: relative;
	z-index: 1;
}

.task-container-glass {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
	padding: 24px;
}

.task-items {
	display: grid;
	grid-template-columns: repeat(3, 1fr); /* 固定一行三个 */
	gap: 20px;
	width: 100%;
}

.task-items>* {
	/* 删除flex相关属性，使用grid布局控制 */
	box-sizing: border-box;
	transition: transform 0.3s, box-shadow 0.3s;
}

.task-items>*:hover {
	transform: translateY(-5px);
	box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.pagination-wrapper {
	margin-top: 20px;
	display: flex;
	justify-content: center;
}

/* 添加分页样式 */
:deep(.el-pagination) {
	color: white;
	/* 设置页码字体颜色为白色 */
}

:deep(.el-pagination.is-background button),
:deep(.el-pagination.is-background .el-pager li) {
	background: rgba(255, 255, 255, 0.05);
	border: 1px solid rgba(255, 255, 255, 0.08);
	color: #e6e8f0;
	/* 设置按钮和页码的字体颜色 */
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
	background: rgba(74, 128, 255, 0.2);
	border-color: rgba(74, 128, 255, 0.3);
	color: #7a9dff;
	/* 设置当前页码的字体颜色 */
}

:deep(.el-pagination.is-background button:hover),
:deep(.el-pagination.is-background .el-pager li:hover) {
	background: rgba(255, 255, 255, 0.1);
	color: #ffffff !important;
	/* 设置悬停时的字体颜色 */
}

@media (max-width: 1200px) {
  .content-wrapper {
    padding: 16px 10px;
  }
  .task-items {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
}
@media (max-width: 800px) {
  .content-wrapper {
    padding: 8px 2px;
  }
  .task-container-glass {
    flex-direction: column;
    padding: 10px 2px;
    gap: 10px;
  }
  .task-items {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .task-items>* {
    min-width: 0;
    max-width: 100%;
  }
  .pagination-wrapper {
    margin-top: 10px;
  }
}
:deep(.el-dialog) {
  @media (max-width: 800px) {
    width: 96vw !important;
    min-width: 0 !important;
    max-width: 100vw !important;
    left: 2vw !important;
    right: 2vw !important;
    margin: 0 !important;
    padding: 0 !important;
  }
}
.dialog-footer.btn-row {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  gap: 12px;
  padding: 8px 0 0 0;
}
@media (max-width: 800px) {
  .dialog-footer.btn-row {
    gap: 8px;
    padding: 4px 0 0 0;
  }
  .dialog-footer.btn-row .el-button {
    flex: 1 1 0;
    min-width: 0;
    font-size: 15px;
    padding-left: 0;
    padding-right: 0;
  }
}
</style>
